package com.bd.scm.module.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.scm.dao.mapper.user.DtFaceMapper;
import com.bd.scm.domain.dto.user.PersonnelFilesDto;
import com.bd.scm.domain.models.log.WtPublic;
import com.bd.scm.domain.models.user.DtFace;
import com.bd.scm.domain.models.user.DtUser;
import com.bd.scm.domain.models.user.UserInfo;
import com.bd.scm.module.log.service.IWtPublicService;
import com.bd.scm.module.user.service.IDtUserService;
import com.bd.scm.module.user.service.IFaceService;
import com.bd.scm.module.utils.FtpUtil;
import com.bd.scm.module.utils.image.ImageUtil;
import com.bd.scm.module.utils.image.ImageZipUtil;
import com.bd.utils.DateUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Slf4j
@Service
public class FaceServiceImpl extends ServiceImpl<DtFaceMapper, DtFace> implements IFaceService {

    @Autowired
    private DtFaceMapper dtFaceMapper;

//    @Autowired
//    private PersonFilesService personFilesService;

    @Autowired
    private IDtUserService iDtUserService;

    @Autowired
    private IWtPublicService iWtPublicService;

    @Value("${bd.upload.facePath}")
    private String facePath;

    @Value("${bd.upload.faceMakeFile}")
    private String faceMakeFile;

    @Value("${bd.upload.takePhotoPath}")
    private String takePhotoPath;

    @Value("${bd.upload.tempfacePhotosDir}")
    private String tempfacePhotosDir;

    //tomcat/bin路径
    @Value("${bd.upload.tomcatBinPath}")
    private String tomcatBinPath;

    //tomcat路径
    @Value("${bd.upload.tomcatPath}")
    private String tomcatPath;

    @Value("${bd.ftp.host}")
    private String host;

    @Value("${bd.ftp.port}")
    private Integer port;

    @Value("${bd.ftp.userName}")
    private String userName;

    @Value("${bd.ftp.password}")
    private String password;

    /**
     * 新增数据
     *
     * @param face
     * @return
     */
    @Override
    public int add(DtFace face) {
        return dtFaceMapper.insert(face);
    }

    /**
     * 根据用户ID获取数据
     *
     * @param userId
     * @return
     */
    @Override
    public DtFace getByUserId(Long userId) {
        return dtFaceMapper.selectOne(new QueryWrapper<DtFace>().eq("user_serial", userId));
    }

    /**
     * 新增用户和人脸照片
     *
     * @param files
     * @param userDto
     */
    @Override
    @Transactional
    public DtUser addUserWithFace(List<MultipartFile> files, PersonnelFilesDto userDto, String clientIp) throws IOException {

        //根据身份证号码获取员工信息
        DtUser user = iDtUserService.getByIdCard(userDto.getUserId());

        if (user == null) {
            //新增员工数据
            Date now = new Date();
            userDto.setPactBegin(DateUtil.format(now, "yyyy-MM-dd").substring(0,10));
            userDto.setPactEnd(DateUtil.format(DateUtils.addDays(now, 30), "yyyy-MM-dd").substring(0,10));
            PersonnelFilesDto personnelFilesDto = iDtUserService.addUserInfoByFace(userDto, clientIp);

            user = new DtUser();
            user.setUserSerial(personnelFilesDto.getUserSerial());
            user.setUserNo(personnelFilesDto.getUserNo());
            user.setUserLname(personnelFilesDto.getUserLname());
            user.setDepNo(personnelFilesDto.getDepNo());
            user.setUserDep(personnelFilesDto.getUserDep());
            user.setUserDepname(personnelFilesDto.getDepName());
        } else {

            DtUser userUpdate = new DtUser();
            userUpdate.setUserSerial(user.getUserSerial());
            userUpdate.setUserFace(2);
            iDtUserService.updateById(userUpdate);
        }

        DtFace face = getByUserId(user.getUserSerial());
        if (face == null) {
            //新增人脸数据
            face = new DtFace();
            face.setUserSerial(user.getUserSerial());
            face.setFaceName(user.getUserSerial() + ".fct");
            face.setLx(0);
            face.setFaceType(0);
            face.setSj(new Date());
            add(face);
        }else {
            //删除人脸
            WtPublic logDelete = new WtPublic();
            logDelete.setLx(32);
            logDelete.setLogType(3);
            logDelete.setIsAll(0);
            logDelete.setUserSerial(user.getUserSerial());
            logDelete.setCardSerial(0L);
            logDelete.setNewNumber(0L);
            logDelete.setOldNumber(0L);
            logDelete.setLogSj(new Date());
            logDelete.setLogIp(clientIp);
            logDelete.setGlyNo("yfc");
            iWtPublicService.add(logDelete);
        }

        //保存照片
        for (MultipartFile file : files) {

            //人脸照片命名：【user_serial】_0.jpg    例：20092184_0.jpg
            String fileName = user.getUserSerial() + "_0.jpg";
            String photoFilePath = facePath + File.separator + (user.getUserSerial() / 1000) + File.separator + File.separator;

            //照片文件夹名：user_serial除以1000    例：20092
            String destFileName = photoFilePath + fileName;

            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();

            file.transferTo(destFile);

            //生成fct文件,调用一卡通自带工具生成
            String fctFileName = photoFilePath + user.getUserSerial() + ".fct";

            String cmd = faceMakeFile + " " + destFileName;

            Process p = Runtime.getRuntime().exec(cmd);
            InputStream fis = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
            }

            File fctFile = new File(fctFileName);

            if (fctFile.exists()) {
                log.info("上传人脸照片成功: {}", fctFileName);
            } else {
                log.info("上传人脸照片失败: {}", fctFileName);
            }
        }

        //插入日志
        WtPublic log1 = new WtPublic();
        log1.setLx(32);
        log1.setLogType(1);
        log1.setIsAll(0);
        log1.setUserSerial(user.getUserSerial());
        log1.setCardSerial(0L);
        log1.setNewNumber(0L);
        log1.setOldNumber(0L);
        log1.setLogSj(new Date());
        log1.setLogIp(clientIp);
        log1.setGlyNo("yfc");
        iWtPublicService.add(log1);

        log1 = new WtPublic();
        log1.setLx(1);
        log1.setLogType(2);
        log1.setIsAll(0);
        log1.setUserSerial(user.getUserSerial());
        log1.setCardSerial(0L);
        log1.setNewNumber(0L);
        log1.setOldNumber(0L);
        log1.setLogSj(new Date());
        log1.setLogIp(clientIp);
        log1.setGlyNo("yfc");
        iWtPublicService.add(log1);

        return user;
    }

    @Override
    public Boolean takePhoto(MultipartFile file, UserInfo userInfo) throws IOException {
        //保存照片
        String fileName = userInfo.getUserNo() + ".jpg";
        String destFileName = takePhotoPath + File.separator + userInfo.getDeptName() + File.separator + fileName;
        File destFile = new File(destFileName);
        destFile.getParentFile().mkdirs();
        file.transferTo(destFile);
        return true;
    }
    /**
     * 导入人脸照片2
     * 修改人脸上传到ftp服务器 lengnianguo 20240129
     * @param clentIp
     */
    @SneakyThrows
    @Override
    @Transactional
    public JSONObject addFace(MultipartFile f, String clentIp, String loginer) throws IOException {

        String ex = f.getOriginalFilename().substring(f.getOriginalFilename().lastIndexOf("."));
        //图片翻转90
        int angle =  ImageUtil.getAngle(ImageUtil.getExif(f.getInputStream()));
        BufferedImage bf =ImageUtil.getBufferedImg(ImageIO.read(f.getInputStream()), ImageUtil.getWidth(f.getInputStream()), ImageUtil.getHeight(f.getInputStream()), angle);

        JSONObject logFace = new JSONObject();
        // 人员ID
        logFace.put("userSerial",loginer);
        //导入编号
        String importNo = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS").substring(0, 16);
        Long userId = 0L;
        String bz = null;
        Integer logState = 1;

        Integer success = 0;
        Integer fail = 0;
        logState = 1;
        bz = null;
        userId = 0L;
        //1.根据照片名称获取人员，找不到直接跳过
        //2.过滤掉后缀不是jpg或JPG或JPEG、jpeg的,直接跳过
        // 都需要存日志
        String originalFileName = f.getOriginalFilename();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_serial", loginer);
        DtUser user = iDtUserService.getOne(queryWrapper);
        if (null != user) {
            // 人员工号
            logFace.put("userNo",user.getUserNo());
            userId = user.getUserSerial();
            String suffix =
                    originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase(Locale.ROOT);
            if (suffix.equals("jpg") || suffix.equals("jpeg")) {
                //人脸照片命名：【user_serial】_0.jpg    例：20092184_0.jpg
                String fileName = user.getUserSerial() + "_0.jpg";

                //上传到ftp服务器的路径
                String photoFilePath = facePath + (user.getUserSerial() / 1000);

                // 本地临时文件的存储路径
                String tempfacePhotosPath = tempfacePhotosDir + File.separator+ fileName;

                // 判断是否存在该照片
                File tempfacePhotosPathFile = new File(tempfacePhotosPath);

                //图片存在删除
                if(tempfacePhotosPathFile.exists()){
                    // 删除图片
                    tempfacePhotosPathFile.delete();
                }
                //将前端传过来的人脸图片复制到临时文件中
                FileUtils.copyFile(multipartFileToFile(f), tempfacePhotosPathFile);

                //将反转后的图片替换到临时文件里面的人脸
                ImageIO.write(bf, ex.substring(1), tempfacePhotosPathFile);

                //将临时文件压缩
                File file = ImageZipUtil.zipImageFile(tempfacePhotosPathFile, tempfacePhotosPathFile, 480, 640, 0.7f);

                //获取ftp服务
                FTPClient ftpClient = FtpUtil.getFtpClient(host, port, userName, password);

                // 在ftp服务上创建多级目录
                String[] dirs = photoFilePath.split("\\\\");
                for (String dir : dirs) {
                    if (dir.isEmpty()) continue;
                    assert ftpClient != null;
                    if (!ftpClient.changeWorkingDirectory(dir)) {
                        ftpClient.makeDirectory(dir);
                        ftpClient.changeWorkingDirectory(dir);
                    }
                }
                //关闭ftp服务
                FtpUtil.disConnect(ftpClient);
                FTPClient ftpClientUpload = FtpUtil.getFtpClient(host, port, userName, password);
                //将人脸上传到ftp服务器
                FtpUtil.upload(ftpClientUpload,file,photoFilePath);
                //生成fct文件
                String fctFileName = tempfacePhotosDir + "\\"+ user.getUserSerial() + ".fct";
                String cmd = faceMakeFile + " " + tempfacePhotosPath;
                Process p = Runtime.getRuntime().exec(cmd);
                InputStream fis = p.getInputStream();
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                }
                File fctFile = new File(fctFileName);
                //将fct文件上传到ftp服务上
                FtpUtil.upload(ftpClientUpload,fctFile,photoFilePath);
                //删除本地文件
                tempfacePhotosPathFile.delete();
                fctFile.delete();
                //关闭ftp服务
                FtpUtil.disConnect(ftpClientUpload);
                success += 1;
                logState = 0;
                //成功之后修改人员信息中的user_face=2
                iDtUserService.updateUserFaceById(userId, 2);

                //写dt_face 数据
                DtFace face = getByUserId(user.getUserSerial());
                if (face == null) {
                    //新增人脸数据
                    face = new DtFace();
                    face.setUserSerial(user.getUserSerial());
                    face.setFaceName(user.getUserSerial() + ".fct");
                    face.setLx(0);
                    face.setFaceType(0);
                    face.setSj(new Date());
                    add(face);
                } else {
                    //删除人脸
                    WtPublic logDelete = new WtPublic();
                    logDelete.setLx(32);
                    logDelete.setLogType(3);
                    logDelete.setIsAll(0);
                    logDelete.setUserSerial(user.getUserSerial());
                    logDelete.setCardSerial(0L);
                    logDelete.setNewNumber(0L);
                    logDelete.setOldNumber(0L);
                    logDelete.setLogSj(new Date());
                    logDelete.setLogIp(clentIp);
                    logDelete.setGlyNo(loginer);
                    iWtPublicService.add(logDelete);
                }
                //人脸
                WtPublic logAdd = new WtPublic();
                logAdd.setLx(32);
                logAdd.setLogType(1);
                logAdd.setIsAll(0);
                logAdd.setUserSerial(user.getUserSerial());
                logAdd.setCardSerial(0L);
                logAdd.setNewNumber(0L);
                logAdd.setOldNumber(0L);
                logAdd.setLogSj(new Date());
                logAdd.setLogIp(clentIp);
                logAdd.setGlyNo(loginer);
                iWtPublicService.add(logAdd);

                logAdd.setLx(1);
                logAdd.setLogType(2);
                iWtPublicService.add(logAdd);

                // 插入日志
                iDtUserService.insertBdFaceUploadLog(logFace);
                // 更新人脸上传日期
                iDtUserService.updateUserRlDate(logFace);
            } else {
                //文件格式错误
                bz = "文件格式错误";
                fail += 1;
            }
        } else {
            //人员不存在
            bz = "人员不存在";
            fail += 1;
        }
        //删除tomcat里bin目录下的图片
        String tomcatBinPathTp = tomcatBinPath + originalFileName;
        File tomcatBinPathTpFile = new File(tomcatBinPathTp);
        //图片存在删除
        if(tomcatBinPathTpFile.exists()){
            // 删除图片
            tomcatBinPathTpFile.delete();
        }
        //删除tomcat里的图片
        String tomcatPathTp = tomcatPath + originalFileName;
        File tomcatPathTpFile = new File(tomcatPathTp);
        //图片存在删除
        if(tomcatPathTpFile.exists()){
            // 删除图片
            tomcatPathTpFile.delete();
        }
        JSONObject j = new JSONObject();
        j.put("bz", bz);
        j.put("success", success);
        j.put("fail", fail);
        return j;
    }

    /**
     * 图片回显返回base64编码 lengnianguo 20240129
     * @param userId
     * @param response
     * @return
     */
    @Override
    public String responseFileStream(String userId, HttpServletResponse response) {
        String s = "";
        //人脸照片命名 例：20092184_0.jpg
        String fileName = userId + "_0.jpg";
        //ftp服务器的路径
        String photoFilePath =
                facePath + (Long.parseLong(userId) / 1000);
        String ftpFilePath = photoFilePath+"\\"+fileName;
        InputStream inputStream = null;
        FTPClient ftpClient = null;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();){
            //获取ftp服务
            ftpClient = FtpUtil.getFtpClient(host, port, userName, password);
            assert ftpClient != null;
            inputStream = ftpClient.retrieveFileStream(ftpFilePath);
            if(inputStream != null) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, length);
                }
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                s = Base64.getEncoder().encodeToString(imageBytes);
            }else {
                log.error("未从ftp服务器上获取到人脸信息，userId:{}",userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            FtpUtil.disConnect(ftpClient);
        }
        return s;
    }
//    /**
//     * 导入人脸照片2
//     *
//     * @param clentIp
//     */
//    @SneakyThrows
//    @Override
//    @Transactional
//    public JSONObject addFace(MultipartFile f, String clentIp, String loginer) throws IOException {
//
//        File localFile = new File("d://a.jpg");
//        String ex = f.getOriginalFilename().substring(f.getOriginalFilename().lastIndexOf("."));
//        //图片翻转90
//        int angle =  ImageUtil.getAngle(ImageUtil.getExif(f.getInputStream()));
//        BufferedImage bf =ImageUtil.getBufferedImg(ImageIO.read(f.getInputStream()), ImageUtil.getWidth(f.getInputStream()), ImageUtil.getHeight(f.getInputStream()), angle);
//
////        System.out.println("-------------------- angle:"+angle); 1500 * 1500 480 * 640 不能大于1M 不能小于20k
////        System.out.println("-------------------- localFile:"+localFile.getAbsolutePath());
//
//        JSONObject logFace = new JSONObject();
//        // 人员ID
//        logFace.put("userSerial",loginer);
//        //导入编号
//        String importNo = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS").substring(0, 16);
//        Long userId = 0L;
//        String bz = null;
//        Integer logState = 1;
//
//        Integer success = 0;
//        Integer fail = 0;
//            logState = 1;
//            bz = null;
//            userId = 0L;
//            //1.根据照片名称获取人员，找不到直接跳过
//            //2.过滤掉后缀不是jpg或JPG或JPEG、jpeg的,直接跳过
//            // 都需要存日志
//            String originalFileName = f.getOriginalFilename();
////            String userNo = originalFileName.substring(0, originalFileName.lastIndexOf("."));
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_serial", loginer);
//            DtUser user = iDtUserService.getOne(queryWrapper);
//            if (null != user) {
//                // 人员工号
//                logFace.put("userNo",user.getUserNo());
//                userId = user.getUserSerial();
//                String suffix =
//                        originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase(Locale.ROOT);
//                if (suffix.equals("jpg") || suffix.equals("jpeg")) {
//                    //人脸照片命名：【user_serial】_0.jpg    例：20092184_0.jpg
//                    String fileName = user.getUserSerial() + "_0.jpg";
//                    String photoFilePath =
//                            facePath + File.separator + (user.getUserSerial() / 1000) + File.separator + File.separator;
//                    String destFileName = photoFilePath + fileName;
//                    // 照片存放路径
//                    logFace.put("userPhotoPath",destFileName);
//                    File destFile = new File(destFileName);
//                    destFile.getParentFile().mkdirs();
//                    FileUtils.copyFile(multipartFileToFile(f), destFile);
//
//                    // 2021/4/1 需求重新保存一张到我们自己的文件夹中
//                    // 最新路径
//                    String tempfacePhotosPath =
//                            tempfacePhotosDir + File.separator + fileName;
//                    // 判断是否存在该照片
//                    File tempfacePhotosPathFile = new File(tempfacePhotosPath);
//                    //图片存在删除
//                    if(tempfacePhotosPathFile.exists()){
//                        // 删除图片
//                        tempfacePhotosPathFile.delete();
//                    }
//                    // 复制照片到相关地址
//                    FileUtils.copyFile(multipartFileToFile(f), tempfacePhotosPathFile);
//                    // 2021/4/1
//                    ImageIO.write(bf, ex.substring(1), new File(tempfacePhotosPath));
//                    ImageIO.write(bf, ex.substring(1), new File(destFileName));
//                    ImageZipUtil.zipImageFile(new File(tempfacePhotosPath), new File(tempfacePhotosPath), 480, 640, 0.7f);
//                    ImageZipUtil.zipImageFile(new File(destFileName), new File(destFileName), 480, 640, 0.7f);
////                    //生成fct文件,调用一卡通自带工具生成
//                    String fctFileName = photoFilePath + user.getUserSerial() + ".fct";
//                    String cmd = faceMakeFile + " " + destFileName;
//                    Process p = Runtime.getRuntime().exec(cmd);
//                    InputStream fis = p.getInputStream();
//                    InputStreamReader isr = new InputStreamReader(fis);
//                    BufferedReader br = new BufferedReader(isr);
//                    String line;
//                    while ((line = br.readLine()) != null) {
//                    }
//                    File fctFile = new File(fctFileName);
//
//                    if (fctFile.exists()) {
//                        log.info("上传人脸照片成功: {}", fctFileName);
//                    } else {
//                        log.info("上传人脸照片失败: {}", fctFileName);
//                    }
//                    success += 1;
//                    logState = 0;
//                    //成功之后修改人员信息中的user_face=2
//                    iDtUserService.updateUserFaceById(userId, 2);
//
//                    //写dt_face 数据
//                    DtFace face = getByUserId(user.getUserSerial());
//                    if (face == null) {
//                        //新增人脸数据
//                        face = new DtFace();
//                        face.setUserSerial(user.getUserSerial());
//                        face.setFaceName(user.getUserSerial() + ".fct");
//                        face.setLx(0);
//                        face.setFaceType(0);
//                        face.setSj(new Date());
//                        add(face);
//                    } else {
//                        //删除人脸
//                        WtPublic logDelete = new WtPublic();
//                        logDelete.setLx(32);
//                        logDelete.setLogType(3);
//                        logDelete.setIsAll(0);
//                        logDelete.setUserSerial(user.getUserSerial());
//                        logDelete.setCardSerial(0L);
//                        logDelete.setNewNumber(0L);
//                        logDelete.setOldNumber(0L);
//                        logDelete.setLogSj(new Date());
//                        logDelete.setLogIp(clentIp);
//                        logDelete.setGlyNo(loginer);
//                        iWtPublicService.add(logDelete);
//                    }
//                    //人脸
//                    WtPublic logAdd = new WtPublic();
//                    logAdd.setLx(32);
//                    logAdd.setLogType(1);
//                    logAdd.setIsAll(0);
//                    logAdd.setUserSerial(user.getUserSerial());
//                    logAdd.setCardSerial(0L);
//                    logAdd.setNewNumber(0L);
//                    logAdd.setOldNumber(0L);
//                    logAdd.setLogSj(new Date());
//                    logAdd.setLogIp(clentIp);
//                    logAdd.setGlyNo(loginer);
//                    iWtPublicService.add(logAdd);
//
//                    logAdd.setLx(1);
//                    logAdd.setLogType(2);
//                    iWtPublicService.add(logAdd);
//
//                    // 插入日志
//                    iDtUserService.insertBdFaceUploadLog(logFace);
//                    // 更新人脸上传日期
//                    iDtUserService.updateUserRlDate(logFace);
//                } else {
//                    //文件格式错误
//                    bz = "文件格式错误";
//                    fail += 1;
//                }
//            } else {
//                //人员不存在
//                bz = "人员不存在";
//                fail += 1;
//            }
//        //删除tomcat里的图片
//        String tomcatBinPathTp = tomcatBinPath + originalFileName;
//        File tomcatBinPathTpFile = new File(tomcatBinPathTp);
//        //图片存在删除
//        if(tomcatBinPathTpFile.exists()){
//            // 删除图片
//            tomcatBinPathTpFile.delete();
//        }
//        JSONObject j = new JSONObject();
//        j.put("bz", bz);
//        j.put("success", success);
//        j.put("fail", fail);
//        return j;
//    }

    private List<File> unzip(MultipartFile file) throws IOException {
        //临时文件目录
        if (!(new File(tempfacePhotosDir).isDirectory())) {
            new File(tempfacePhotosDir).mkdirs();
        }
        List<File> listFile = new ArrayList<>();
        byte[] buffer = new byte[1024];
        int bufferSize = 1024;
        ZipInputStream zis = new ZipInputStream(file.getInputStream(), Charset.forName("GBK"));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            File tempFile = new File(tempfacePhotosDir + entry.getName());
            tempFile.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tempFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos, bufferSize);
            int count;
            while ((count = zis.read(buffer, 0, bufferSize)) != -1) {
                bos.write(buffer, 0, count);
            }
            bos.flush();
            bos.close();
            listFile.add(tempFile);
        }
        zis.close();
        return listFile;
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
